const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('Scene/MarchLine/MarchLine')
export default class MarchLine extends cc.Component {

    @property({ type: cc.Node, tooltip: 'start point' })
    startPoint: cc.Node = null;

    @property({ type: cc.Node, tooltip: 'end' })
    endPoint: cc.Node = null;

    @property({ type: cc.Prefab, tooltip: 'line cell' })
    lineCell: cc.Prefab = null;

    start() {
        let len = this.calcPointDistance(this.startPoint.position, this.endPoint.position);

        let midPoint = this.calcMidPoint(this.startPoint.position, this.endPoint.position);

        let theta = this.calcPointAngle(this.startPoint.position, this.endPoint.position);

        let lineNode = cc.instantiate(this.lineCell);
        lineNode.position = midPoint;
        lineNode.width = len;
        lineNode.angle = theta;
        lineNode.parent = this.node;
    }

    calcPointDistance(start: cc.Vec3, end: cc.Vec3) {
        return start.sub(end).mag();
    }

    calcMidPoint(start: cc.Vec3, end: cc.Vec3) {
        let x = (start.x + end.x) / 2;
        let y = (start.y + end.y) / 2;

        return new cc.Vec3(x, y, 1);
    }

    calcPointAngle(p1: cc.Vec3, p2: cc.Vec3) {
        let angle: number = Math.atan2((p1.y - p2.y), (p2.x - p1.x));
        var theta: number = angle * (180 / Math.PI) * -1;

        return theta;
    }
}
